#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""只读扫描：汇总用户资料字段在后端与小程序前端的引用情况。
输出 JSON: temp_uploads/field_usage_report.json
不修改任何现有代码，安全可回退。
"""
import os, re, json, sys
BASE = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
TARGET_FIELDS = { 'users': [
    'id','username','real_name','mobile','email','gender','birth_date','address','nickname','avatar','openid','user_type','bind_status','student_id','last_login','created_at'
]}
usage = {f: {'backend': 0, 'miniprogram': 0, 'files': []} for f in TARGET_FIELDS['users']}
pattern_cache = {f: re.compile(r'\b'+re.escape(f)+r'\b') for f in usage}

scan_paths = [
    os.path.join(BASE, 'backend'),
    os.path.join(BASE, 'miniprogram')
]

for root_path in scan_paths:
    for root, dirs, files in os.walk(root_path):
        for name in files:
            if not name.endswith(('.py','.js','.wxml','.json','.wxss')):
                continue
            fp = os.path.join(root, name)
            try:
                with open(fp, 'r', encoding='utf-8', errors='ignore') as fh:
                    text = fh.read()
                for field, pat in pattern_cache.items():
                    if pat.search(text):
                        key = 'backend' if 'backend' in root else 'miniprogram'
                        usage[field][key] += 1
                        usage[field]['files'].append(os.path.relpath(fp, BASE))
            except Exception:
                pass

out_dir = os.path.join(BASE, 'temp_uploads')
os.makedirs(out_dir, exist_ok=True)
report_path = os.path.join(out_dir, 'field_usage_report.json')
with open(report_path, 'w', encoding='utf-8') as f:
    json.dump({'entity':'users','usage':usage}, f, ensure_ascii=False, indent=2)
print(f'[audit] field usage report written -> {report_path}')
